<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车牌号" prop="plateNo">
        <el-input
          v-model="queryParams.plateNo"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="车号" prop="numbered">
        <!-- <el-select v-model="queryParams.vehicleId">
            <el-option 
              v-for="option in routeList" 
              :key="option.id" 
              :value="option.id" 
              :label="option.name" 
              />
          </el-select> -->
          <el-input
          v-model="queryParams.numbered"
          placeholder="请输入车牌号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['dispatch:vehicleRouteCross:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dispatch:vehicleRouteCross:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['dispatch:vehicleRouteCross:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['dispatch:vehicleRouteCross:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="vehicleRouteCrossList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车牌号" align="center" prop="plateNo" width="155"/>
      <el-table-column label="车号" align="center" prop="numbered" width="155"/>
      <el-table-column label="线路名称" align="center" prop="routeName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dispatch:vehicleRouteCross:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dispatch:vehicleRouteCross:remove']">删除</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车辆跨线运营配置对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="vehicleRouteCrossRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="车牌号" prop="vehicleId">
          <el-select v-model="form.vehicleId" filterable  :disabled="!isAdd">
            <el-option 
              v-for="option in vehicleList" 
              :key="option.id" 
              :value="option.id" 
              :label="option.plateNo+'('+option.numbered+')'" 
              />
          </el-select>
        </el-form-item>
        <el-button type="primary" class="AddBtn" @click="addRoute">新增运营线路</el-button>
        <el-row v-for="(item,index) in form.list" :key="item.routeId + index">
          <el-col :span="8">
            <el-form-item label="线路选择" :prop="'list.' + index + '.routeId'">
              <el-select v-model="item.routeId">
                <el-option 
                  v-for="option in routeList" 
                  :key="option.id" 
                  :value="option.id" 
                  :label="option.name" 
                  />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运营时间" :prop="'list.' + index + '.operateDay'">
              <el-checkbox-group v-model="item.operateDay">
                <el-checkbox v-for="week in dispatch_week" :key="week.value" :label="week.label" :value="week.value"/>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="danger" @click="deleteList(index)">删除</el-button>
          </el-col>
          <el-divider />
        </el-row>
        <!-- <el-form-item label="线路选择" prop="routeId">
        </el-form-item>
        <el-form-item label="运营时间" prop="operateDay">
          <el-input v-model="form.operateDay" placeholder="请输入运营时间" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="VehicleRouteCross">
import { listVehicleRouteCross, getVehicleRouteCross, delVehicleRouteCross, addVehicleRouteCross, updateVehicleRouteCross } from "@/api/dispatch/vehicleRouteCross";
import { listVehicle } from "@/api/basic/vehicle";
import { listRoute } from "@/api/basic/route";
import { ref } from "vue";
const { proxy } = getCurrentInstance();
const { dispatch_week } = proxy.useDict('dispatch_week');

const vehicleRouteCrossList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    vehicleId: undefined,
    routeId: undefined,
  },
  rules: {
    id: [
      { required: true, message: "不能为空", trigger: "blur" }
    ],
    vehicleId: [
      { required: true, message: "车辆id不能为空", trigger: "blur" }
    ],
    routeId: [
      { required: true, message: "线路id不能为空", trigger: "blur" }
    ],
    operateDay: [
      { required: true, message: "运营时间不能为空", trigger: "blur" }
    ],
    deptId: [
      { required: true, message: "部门ID不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询车辆跨线运营配置列表 */
function getList() {
  loading.value = true;
  listVehicleRouteCross(queryParams.value).then(response => {
    vehicleRouteCrossList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    vehicleId: null,
    routeId: null,
    operateDay: null,
    deptId: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    list:[]
  };
  proxy.resetForm("vehicleRouteCrossRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
const deleteList = (index)=>{
  // log
  if(index){
    form.value.list.splice(index - 1,index)
    return
  }
  form.value.list.shift()
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
const isAdd = ref(false)
/** 新增按钮操作 */
function handleAdd() {
  reset();
  isAdd.value = true
  open.value = true;
  title.value = "添加车辆跨线运营配置";
  addRoute()
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  isAdd.value = false
  const _id = row.vehicleId || ids.value
  getVehicleRouteCross(_id).then(response => {
    loading.value = false;
    form.value = response.data;
    form.value.list.forEach((ele)=>{
      ele.operateDay = ele.operateDay.split(',')
      ele.operateDay.forEach((item,index) => {
        ele.operateDay[index] = '周'.concat(item)
      });
    })
    open.value = true;
    title.value = "修改车辆跨线运营配置";
  });
}
const vehicleList = ref()
/** 查询车辆列表 */
function getlistVehicle() {
  loading.value = true;
  listVehicle().then(response => {
    vehicleList.value = response.rows;
  });
}
getlistVehicle()

const routeList = ref()
/** 查询线路列表 */
function getRouteList() {
  loading.value = true;
  listRoute(queryParams.value).then(response => {
    routeList.value = response.rows;
  });
}
getRouteList()

const addRoute = ()=>{
  form.value.list.push({
    routeId:null,
    operateDay:[]
  })
}
/** 提交按钮 */
function submitForm() {
  const JsonFrom = JSON.parse(JSON.stringify(form.value))
  JsonFrom.list.forEach(ele => {
    console.log(ele.operateDay);
    const str = ele.operateDay.join(',')
    const reg1 = new RegExp("周",'g');
    const response = str.replace(reg1,"");
    ele.operateDay = response
  });
  proxy.$refs["vehicleRouteCrossRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (!isAdd.value) {
        updateVehicleRouteCross(JsonFrom).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addVehicleRouteCross(JsonFrom).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.vehicleId || ids.value;
  proxy.$modal.confirm('是否确认删除车辆跨线运营配置编号为"' + _ids + '"的数据项？').then(function() {
    loading.value = true;
    return delVehicleRouteCross(_ids);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dispatch/vehicleRouteCross/export', {
    ...queryParams.value
  }, `vehicleRouteCross_${new Date().getTime()}.xlsx`)
}

getList();
</script>

<style scoped>
.AddBtn{
  margin-bottom: 10px;
}
</style>
